package com.cdivtc.management.service;


import com.cdivtc.management.dao.LoginLogMapper;
import com.cdivtc.management.dao.SysLogMapper;
import com.cdivtc.management.pojo.IPCity;
import com.cdivtc.management.pojo.LoginLog;
import com.cdivtc.management.pojo.SysLog;
import com.cdivtc.management.pojo.User;
import com.cdivtc.management.utils.IPAddr;
import com.cdivtc.management.utils.IdWorker;
import com.cdivtc.management.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;

@Service
public class LogSever {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private LoginLogMapper loginLogMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private SysLogMapper sysLogMapper;
    @Autowired
    private UserSerive serive;
    String IP_URL_ROOT = "https://api.ip138.com/query/?ip=";
    String datatype = "&datatype=jsonp&callback=find&token=eba80d2f94d8419f3f0008476481b69d";
    private String ip;

    //登录成功日志
    public void loginSuccess(HttpServletRequest request, long time) {
        LoginLog loginLog = new LoginLog();
        loginLog.setLogId(idWorker.nextId() + "");
        ip = IPAddr.getIpAddress(request);
        loginLog.setIpaddr(ip);
        loginLog.setOperationTime(new Date());
        loginLog.setState("1");
        loginLog.setOperationUsername(request.getParameter("username"));
        loginLog.setUsetime(time);
        loginLog.setOperationType("登录成功");
        loginLog.setCity(getIPCity());

        loginLogMapper.insert(loginLog);
    }

    //登录失败日志
    public void loginError(HttpServletRequest request, long time) {
        LoginLog loginLog = new LoginLog();
        loginLog.setLogId(idWorker.nextId() + "");
        ip = IPAddr.getIpAddress(request);
        loginLog.setIpaddr(ip);
        loginLog.setOperationTime(new Date());
        loginLog.setState("1");
        loginLog.setOperationUsername(request.getParameter("username"));
        loginLog.setUsetime(time);
        loginLog.setOperationType("登录失败");
        loginLog.setCity(getIPCity());

        loginLogMapper.insert(loginLog);
    }


    public String getIPCity() {
        URL url = null;
        try {
            url = new URL(IP_URL_ROOT + ip + datatype);
            URLConnection connection = null;
            connection = url.openConnection();
            connection.connect();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str = "";
            StringBuilder sb = new StringBuilder();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            String IPCityJson = sb.toString();
            IPCityJson = IPCityJson.substring(5, IPCityJson.length() - 1);
            System.out.println("IPCityJson = " + IPCityJson);
            IPCity ipCity = JsonUtils.jsonToPojo(IPCityJson, IPCity.class);
            String city = "";
            if (ipCity != null)

                for (String datum : ipCity.getData()) {
                    if (datum == null || "".equals(datum))
                        break;
                    city += datum;
                }
            return city;
        } catch (IOException ex) {
            return "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //    添加用户操作日志
    public void addSysLog(SysLog sysLog, HttpServletRequest request, long time) {
//
        sysLog.setLogId(idWorker.nextId() + "");
        sysLog.setOperationTime(new Date());
        sysLog.setUsedata(time);
        sysLog.setIp(IPAddr.getIpAddress(request));

        sysLogMapper.insert(sysLog);

    }

    //    查询所有登录日志
    public List<LoginLog> queryAllLogin() {
        List<LoginLog> loginLogs = loginLogMapper.selectAll();
        return loginLogs;

    }

    //    根据 用户名查登录日志
    public  List<LoginLog> queryByUsernameLogin(String username) {

        User byUid = serive.findByUid(username);
        LoginLog loginLog = new LoginLog();
        loginLog.setOperationUsername(byUid.getUsername());
        List<LoginLog> loginLogs = loginLogMapper.select(loginLog);

        return loginLogs;
    }

    //查询所有操作日志
    public List<SysLog> queryAllSysLog() {
        return sysLogMapper.selectAll();
    }


    //    根据用户名查找操作日志
    public List<SysLog> queryByUsernameSys(String username) {
        SysLog loginLog = new SysLog();
        loginLog.setOperationUsername(username);
        List<SysLog> loginLogs = sysLogMapper.select(loginLog);
        return loginLogs;
    }

    //   管理员 删除所有登录日志
    public void deleteAllLoginLog() {
        loginLogMapper.delete(new LoginLog());
    }

    //   管理员用户删除单个日志
    public void deleteOneByLoginid(String logid) {

        loginLogMapper.deleteByPrimaryKey(logid);
    }
//  管理员删除单个用户所有日志

    public void deleteOneByUsername(String username) {


        LoginLog loginLog = new LoginLog();
        loginLog.setOperationUsername(username);
        loginLogMapper.delete(loginLog);
    }

    //    管理员删除所有操作日志
    public void deleteAllSys() {
        sysLogMapper.delete(new SysLog());
    }

    //    用户删除单个操作日志
    public void deleteOneBySysId(String logid) {

        sysLogMapper.deleteByPrimaryKey(logid);
    }

    //   删除单个用户所有日志

    public void deleteOneBySysUsername(String username) {
        SysLog loginLog = new SysLog();
        loginLog.setOperationUsername(username);
        sysLogMapper.delete(loginLog);
    }


}
